package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.response.AgentCategoryDetailResponse;
import com.zbkj.common.response.AgentCategoryListResponse;
import com.zbkj.common.response.AgentCategoryPageDataResponse;
import com.zbkj.common.request.AgentCategorySearchRequest;
import com.zbkj.common.request.AgentCategorySaveRequest;

import com.zbkj.common.response.BrandAgentCategoryPageDataResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.AgentCategory;
import com.zbkj.service.dao.AgentCategoryDao;
import com.zbkj.service.service.AgentCategoryService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.util.BrandUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dazongzi
* @description AgentCategoryServiceImpl 接口实现
* @date 2025-07-01
*/
@Service
public class AgentCategoryServiceImpl extends ServiceImpl<AgentCategoryDao, AgentCategory> implements AgentCategoryService {

    @Resource
    private AgentCategoryDao dao;

    @Override
    public Boolean create(AgentCategorySaveRequest agentCategorySaveRequest) {
        AgentCategory agentCategory = new AgentCategory();
        BeanUtils.copyProperties(agentCategorySaveRequest, agentCategory, "id");
        agentCategory.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(agentCategory);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询代理分类表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<AgentCategory>
     * @author dazongzi
     * @since 2025-07-01
     */
    @Override
    public List<AgentCategoryPageDataResponse> getList(AgentCategorySearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 AgentCategory 类的多条件查询
        LambdaQueryWrapper<AgentCategory> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(request.getCategoryName())) {
            lambdaQueryWrapper.like(AgentCategory::getCategoryName, request.getCategoryName());
        }

        lambdaQueryWrapper.eq(AgentCategory::getBrandId, 0);
        lambdaQueryWrapper.eq(AgentCategory::getIsDel, false);
        lambdaQueryWrapper.orderByAsc(AgentCategory::getSort);
        List<AgentCategory> agentCategorys = dao.selectList(lambdaQueryWrapper);
        List<AgentCategoryPageDataResponse> agentCategoryResponses = new ArrayList<>();

        agentCategorys.stream().forEach(x->{
            AgentCategoryPageDataResponse agentCategoryResponse = new AgentCategoryPageDataResponse();
            BeanUtils.copyProperties(x, agentCategoryResponse);
            agentCategoryResponses.add(agentCategoryResponse);
        });
        return agentCategoryResponses;
    }

    @Override
    public List<BrandAgentCategoryPageDataResponse> getListBrand(AgentCategorySearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带 AgentCategory 类的多条件查询
        LambdaQueryWrapper<AgentCategory> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(request.getCategoryName())) {
            lambdaQueryWrapper.like(AgentCategory::getCategoryName, request.getCategoryName());
        }

        lambdaQueryWrapper.eq(AgentCategory::getIsDel, false);
        lambdaQueryWrapper.orderByAsc(AgentCategory::getBrandId);
        lambdaQueryWrapper.orderByAsc(AgentCategory::getSort);
        List<AgentCategory> agentCategorys = dao.selectList(lambdaQueryWrapper);
        List<BrandAgentCategoryPageDataResponse> agentCategoryResponses = new ArrayList<>();

        agentCategorys.stream().forEach(x->{
            BrandAgentCategoryPageDataResponse agentCategoryResponse = new BrandAgentCategoryPageDataResponse();
            BeanUtils.copyProperties(x, agentCategoryResponse);
            if (x.getBrandId() != null && x.getBrandId() == 0) {
                agentCategoryResponse.setIsNotUpdate(true);
            }
            agentCategoryResponses.add(agentCategoryResponse);
        });
        return agentCategoryResponses;
    }

    @Override
    public List<AgentCategoryListResponse> getAllList() {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.eq(AgentCategory::getBrandId, 0);
        checkWrapper.orderByAsc(AgentCategory::getSort);
        List<AgentCategory> list = list(checkWrapper);
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<AgentCategoryListResponse> responseList = list.stream().map(e -> {
            AgentCategoryListResponse articleResponse = new AgentCategoryListResponse();
            BeanUtils.copyProperties(e, articleResponse);
            return articleResponse;
        }).collect(Collectors.toList());
        return responseList;
    }

    @Override
    public String getNameById(Integer categoryId) {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.eq(AgentCategory::getId, categoryId);
        AgentCategory one = getOne(checkWrapper);
        if (ObjectUtil.isNotNull(one)) {
            return one.getCategoryName();
        }
        return null;
    }

    @Override
    public List<AgentCategory> getListPlatform() {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.eq(AgentCategory::getBrandId, 0);
        checkWrapper.orderByAsc(AgentCategory::getSort);
        return list(checkWrapper);
    }
    @Override
    public List<AgentCategory> getListPlatformAndBrand(Integer brandId) {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.in(AgentCategory::getBrandId, 0, brandId);
        checkWrapper.orderByAsc(AgentCategory::getBrandId);
        checkWrapper.orderByAsc(AgentCategory::getSort);
        return list(checkWrapper);
    }

    @Override
    public AgentCategory getIdBySn(String categorySn) {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.select(AgentCategory::getId);
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.eq(AgentCategory::getCategorySn, categorySn);
        AgentCategory one = getOne(checkWrapper);
        if (ObjectUtil.isNotNull(one)) {
            return one;
        }
        return null;
    }

    /**
     * 批量删除
     * @param idList
     * @return
     */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<AgentCategory> luw = Wrappers.lambdaUpdate();
        luw.set(AgentCategory::getIsDel, true);
        luw.in(AgentCategory::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除代理分类失败"));
        }
        return true;
    }

    @Override
    public boolean batchDeleteBrand(List<Integer> idList) {
        existsPlatformData(idList);

        LambdaUpdateWrapper<AgentCategory> luw = Wrappers.lambdaUpdate();
        luw.set(AgentCategory::getIsDel, true);
        luw.in(AgentCategory::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除代理分类失败"));
        }
        return true;
    }

    private void existsPlatformData(List<Integer> idList) {
        LambdaQueryWrapper<AgentCategory> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(AgentCategory::getBrandId, 0);
        checkWrapper.eq(AgentCategory::getIsDel, 0);
        checkWrapper.in(AgentCategory::getId, idList);
        long count = this.count(checkWrapper);
        if (count > 0) {
            throw new AppException("平台数据不能删除");
        }
    }

    /**
     * 修改代理分类表
     * @param request
     * @return
     */
    @Override
    public boolean update(AgentCategorySaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入代理分类ID");
        }
        getByIdException(request.getId());
        AgentCategory agentCategory = new AgentCategory();
        BeanUtils.copyProperties(request, agentCategory);
        return updateById(agentCategory);
    }

    @Override
    public boolean updateBrand(AgentCategorySaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入代理分类ID");
        }
        AgentCategory agentCategoryTmp = getByIdException(request.getId());
        if (agentCategoryTmp.getBrandId() == null || agentCategoryTmp.getBrandId() == 0) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "平台数据不允许修改");
        }
        AgentCategory agentCategory = new AgentCategory();
        BeanUtils.copyProperties(request, agentCategory);
        return updateById(agentCategory);
    }

    private AgentCategory getByIdException(Integer id) {
        AgentCategory agentCategory = getById(id);
        if (ObjectUtil.isNull(agentCategory)) {
            throw new AppException("代理分类不存在");
        }
        if (agentCategory.getIsDel()) {
            throw new AppException("代理分类不存在");
        }
        return agentCategory;
    }

    /**
     * 查询详情
     * @param id
     * @return
     */
    @Override
    public AgentCategoryDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<AgentCategory> lqw = Wrappers.lambdaQuery();
        lqw.eq(AgentCategory::getIsDel, 0);
        lqw.eq(AgentCategory::getBrandId, 0);
        lqw.eq(AgentCategory::getId, id);
        lqw.last("limit 1");
        AgentCategory agentCategory = this.getOne(lqw);
        if (ObjectUtil.isNotNull(agentCategory)) {
            AgentCategoryDetailResponse response = new AgentCategoryDetailResponse();
            BeanUtils.copyProperties(agentCategory, response);
            return response;
        }
        return null;
    }

    @Override
    public AgentCategoryDetailResponse getDetailsBrand(Integer id) {
        LambdaQueryWrapper<AgentCategory> lqw = Wrappers.lambdaQuery();
        lqw.eq(AgentCategory::getIsDel, 0);
//        lqw.eq(AgentCategory::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.eq(AgentCategory::getId, id);
        lqw.last("limit 1");
        AgentCategory agentCategory = this.getOne(lqw);
        if (ObjectUtil.isNotNull(agentCategory)) {
            AgentCategoryDetailResponse response = new AgentCategoryDetailResponse();
            BeanUtils.copyProperties(agentCategory, response);
            return response;
        }
        return null;
    }

}

